package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.sysConfig.SysConfigChildrenOne;
import com.itheima.ydd.dto.sysConfig.SysConfigChildrenTWo;
import com.itheima.ydd.dto.sysConfig.SysConfigDto;
import com.itheima.ydd.dto.sysConfig.SysConfigDtoAll;
import com.itheima.ydd.entity.SysConfig;
import com.itheima.ydd.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 前端控制器
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/sys_config")
@CrossOrigin
@Slf4j
public class SysConfigController {
    @Autowired
    private ISysConfigService sysConfigService;
    //List最外层的集合
    private List<SysConfigChildrenOne> sysConfigChildrens = new ArrayList<>();

    //基础配置集合
    private List<SysConfigChildrenTWo> baseList = new ArrayList<>();
    //其他配置集合
    private List<SysConfigChildrenTWo> customList = new ArrayList<>();
    //系统配置集合
    private List<SysConfigChildrenTWo> systemList = new ArrayList<>();

    /**
     * 获得所有系统配置数据
     *
     * @return
     */
    @GetMapping("/all")
    public ResultData all() {
        sysConfigChildrens = new ArrayList<>();
        baseList = new ArrayList<>();
        customList = new ArrayList<>();
        systemList = new ArrayList<>();
        //1.allData数据
        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<>();
        lqw.select(SysConfig::getId, SysConfig::getAttrKey, SysConfig::getAttrValue, SysConfig::getConfigValue, SysConfig::getType, SysConfig::getValidator);
        List<SysConfig> allDateList = sysConfigService.list(lqw);

        //2.configForm数据
        LambdaQueryWrapper<SysConfig> lqw1 = new LambdaQueryWrapper<>();
        lqw1.select(SysConfig::getAttrKey, SysConfig::getAttrValue);
        Map<String, String> configFormMap = new HashMap<>();
        List<SysConfig> configs1 = sysConfigService.list(lqw1);
        for (SysConfig sysConfig : configs1) {
            configFormMap.put(sysConfig.getAttrKey(), sysConfig.getAttrValue());
        }

        //3.configRule数据
        LambdaQueryWrapper<SysConfig> lqw2 = new LambdaQueryWrapper<>();
        //查询site_name
        lqw2.isNotNull(SysConfig::getValidator).ne(SysConfig::getValidator, "");
        SysConfig sysConfig = sysConfigService.getOne(lqw2);
        Map<String, String> configRuleMap = new HashMap<>();
        //configRule数据
        if (sysConfig != null) {
            configRuleMap.put(sysConfig.getAttrKey(), sysConfig.getValidator());
        }

        //4.List数据
        LambdaQueryWrapper<SysConfig> lqw4 = new LambdaQueryWrapper<>();
        //1)根据table_value字段进行分组
        lqw4.groupBy(SysConfig::getTabValue);
        //2)查询出分组之后的分类
        List<SysConfig> tabValue = sysConfigService.list(lqw4);
        for (SysConfig config : tabValue) {
            //3)利用循环构建查询构造器
            LambdaQueryWrapper<SysConfig> lqw5 = new LambdaQueryWrapper<>();
            //4)查出单个分组
            lqw5.eq(SysConfig::getTabValue, config.getTabValue());
            //5)获得每个分组的集合
            List<SysConfig> configs = sysConfigService.list(lqw5);
            for (SysConfig category : configs) {
                //查询出base分组下的所有数据
                if ("base".equals(category.getTabValue())) {
                    //新建一个List的第一层级的对象
                    SysConfigChildrenOne sysConfigChildrenOne = new SysConfigChildrenOne();
                    //构建Tab英文标识
                    sysConfigChildrenOne.setKey("base");
                    //构建Tab标签名称
                    sysConfigChildrenOne.setName("基础设置");
                    //设置第一层级的children数据
                    setChildren(configs);
                    //存入第一层级对象
                    sysConfigChildrenOne.setChildren(baseList);
                    sysConfigChildrens.add(sysConfigChildrenOne);
                    break;
                } else if ("custom".equals(category.getTabValue())) {
                    SysConfigChildrenOne sysConfigChildrenOne = new SysConfigChildrenOne();
                    sysConfigChildrenOne.setKey("custom");
                    sysConfigChildrenOne.setName("其他设置");
                    setChildren(configs);
                    sysConfigChildrenOne.setChildren(customList);
                    sysConfigChildrens.add(sysConfigChildrenOne);
                    break;
                } else if ("system".equals(category.getTabValue())) {
                    SysConfigChildrenOne sysConfigChildrenOne = new SysConfigChildrenOne();
                    sysConfigChildrenOne.setKey("system");
                    sysConfigChildrenOne.setName("系统设置");
                    setChildren(configs);
                    sysConfigChildrenOne.setChildren(systemList);
                    sysConfigChildrens.add(sysConfigChildrenOne);
                    break;
                }
            }
        }
        //返回页面需要的数值
        SysConfigDtoAll sysConfigDtoAll = new SysConfigDtoAll();
        sysConfigDtoAll.setAllData(allDateList);
        sysConfigDtoAll.setConfigForm(configFormMap);
        sysConfigDtoAll.setConfigRules(configRuleMap);
        sysConfigDtoAll.setList(sysConfigChildrens);
        return ResultData.ok("数据查询成功", sysConfigDtoAll);
    }

    //List第一层结构：配置数据
    private void setChildren(List<SysConfig> list) {
        //遍历每个分组的集合
        for (SysConfig sysConfig : list) {
            //获得每一个分组
            String tabValue = sysConfig.getTabValue();
            //获得本分组下的group_value的两个数据
            String groupValue = sysConfig.getGroupValue();
            l:
            switch (tabValue) {
                case "base":
                    //遍历基础配置集合
                    for (SysConfigChildrenTWo childrenTWo : baseList) {
                        //进行循环比对
                        if (childrenTWo.getName().equals(groupValue)) {
                            break l;
                        }
                    }
                    //用SysConfigDto继承的SysConfig将数据赋值进去，并设置上设置分组名
                    MessageTwo(groupValue, "base");
                    break;
                case "custom":
                    for (SysConfigChildrenTWo childrenTWo : customList) {
                        if (childrenTWo.getName().equals(groupValue)) {
                            break l;
                        }
                    }

                    MessageTwo(groupValue, "custom");
                    break;
                case "system":
                    for (SysConfigChildrenTWo childrenTWo : systemList) {
                        if (childrenTWo.getName().equals(groupValue)) {
                            break l;
                        }
                    }

                    MessageTwo(groupValue, "system");
                    break;
            }
        }
    }

    //list第二层结构：children子集元素
    public void MessageTwo(String groupValue, String listName) {
        //创建数据对象name和List<SysConfigChild> data
        SysConfigChildrenTWo childrenTWo = new SysConfigChildrenTWo();
        //设置数据的名字
        childrenTWo.setName(groupValue);
        //构造条件构造器
        LambdaQueryWrapper<SysConfig> lqw = new LambdaQueryWrapper<>();
        //根据名字查询
        lqw.eq(SysConfig::getGroupValue, groupValue);
        List<SysConfig> list = sysConfigService.list(lqw);
        //封装configValueMap字段
        List<Map<String, String>> list1 = new ArrayList<>();

        //遍历list
        List<SysConfigDto> sysConfigDtoList = list.stream().map((item) -> {
            //获得group_value
            String configValue = item.getConfigValue();
            if (configValue != null && configValue.length() != 0) {
                //将config_value不为空的内容封装成一个字符串数组
                String[] split = configValue.split("&");
                //遍历字符串数组
                for (String str : split) {
                    //调用okOrErr方法将是否存入map集合
                    Map<String, String> map = okOrErr(str);
                    list1.add(map);
                }
            }
            //将SysConfig数据复制到SysConfigChild中
            SysConfigDto sysConfigChild = new SysConfigDto();
            BeanUtils.copyProperties(item, sysConfigChild);
            //设置config_value的值
            sysConfigChild.setConfigValueMap(list1);
            return sysConfigChild;
        }).collect(Collectors.toList());

        //将SysConfig存进去
        childrenTWo.setData(sysConfigDtoList);
        //将数据添加进去
        if (listName.equals("base")) {
            baseList.add(childrenTWo);
        } else if (listName.equals("custom")) {
            customList.add(childrenTWo);
        } else if (listName.equals("system")) {
            systemList.add(childrenTWo);
        }
    }

    //传出对:1 否:2
    private Map<String, String> okOrErr(String str) {
        Map<String, String> map = new HashMap();
        String[] split = str.split("=");
        map.put("label", split[0]);
        map.put("value", split[1]);
        return map;
    }

    /**
     * 更新配置
     *
     * @param configs
     * @return
     */
    @PostMapping("update")
    public ResultData update(@RequestBody List<SysConfig> configs) {
        sysConfigService.updateBatchById(configs);
        return ResultData.ok("修改成功", configs);
    }

}